package com.itwlj.controller.listener;

import com.itwlj.constant.MqConstant;
import com.itwlj.constant.StatusConstant;
import com.itwlj.entity.Order;
import com.itwlj.entity.OrderGoods;
import com.itwlj.mapper.OrderMapper;
import com.itwlj.service.OrderService;
import com.itwlj.service.SkuService;
import com.itwlj.vo.OrderVO;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
public class OrderDelayMessageListener {

    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private SkuService skuService;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = MqConstant.ORDER_TIMEOUT_DELAY_QUEUE),
            exchange = @Exchange(name = MqConstant.ORDER_TIMEOUT_DELAY_EXCHANGE, delayed = "true"),
            key = MqConstant.ORDER_TIMEOUT_DELAY_ROUTING_KEY
    ))
    public void listenOrderDelayMessage(Long orderId){
        // 1.查询订单
        OrderVO orderVO = orderService.getById(orderId);
        System.out.println("listener：orderId="+orderId);
        // 2.检测订单状态
        if(orderVO == null || !orderVO.getOrderState().equals(StatusConstant.ORDER_UNPAID)){
            // 订单不存在或者已经支付
            return;
        }
        // 3.未支付，设置订单状态为取消
        Order order = new Order();
        order.setId(orderId);
        order.setOrderState(StatusConstant.ORDER_CLOSE);
        order.setPayResult(StatusConstant.ORDER_PAYMENT_FAILED);
        order.setCloseTime(LocalDateTime.now());
        orderMapper.update(order);

        // 4.回滚库存
        List<OrderGoods> orderGoodsList = orderVO.getOrderGoodsList();
        orderGoodsList.forEach(orderGoods -> {
            Long skuId = orderGoods.getSkuId();
            Long count = (long) orderGoods.getCount();
            skuService.backInventory(skuId, count);
        });
    }
}
